const Redis = require('ioredis');
const {ENV} = require('../config')
const {UnifiedConfigurationCenter} = require('../util/unified_configuration_center')


async function getRedisDb(){
    const value = await new UnifiedConfigurationCenter().get_value('TCBase.Cache.v2');
    const hostPorts = JSON.parse(value)[0]['instances'];
    const redisDb = [];
    hostPorts.forEach(obj=>{
        const ipSplit = obj.ip.split(':');
        redisDb.push({host: ipSplit[0], port:ipSplit[1]})
    });
    return redisDb;
}

class RedisClient {
    async getConn(){
        let conn;
        if (ENV === 'local') {
            conn = new Redis({
                port: 6379, // Redis port
                host: "127.0.0.1", // Redis host
                family: 4, // 4 (IPv4) or 6 (IPv6)
                db: 0,
            });
        } else {
            const redisDb = await getRedisDb();
            conn = new Redis.Cluster(redisDb, {
                redisOptions: {
                    password: null,
                }
            });
        }
        return conn;
    }
}

// async function test(){
//     // 清理redis缓存
//     const conn = await new RedisClient().getConn();
//     const res = await conn.flushall();
//     console.log(res);
// }
// test();

module.exports = {
    RedisClient: RedisClient
}